package com.hwd.gmall.payment.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayUtil;
import com.hwd.gmall.payment.service.WeiXinPayService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付业务的控制层
 *
 * @author 黄伟东/Victor
 * @date 2022/5/10 20:32
 */
@RestController
@RequestMapping(value = "/weixin/pay")
public class WeiXinPayController {

    @Resource
    private WeiXinPayService weiXinPayService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 获取微信支付二维码的接口
     * @param orderMap 参数
     * @return java.util.Map<java.lang.String,java.lang.String>
     */
    @PostMapping(value = "/getPayUrl")
    public Map<String, String> getPayUrl(@RequestParam Map<String,String> orderMap) {
        return weiXinPayService.getWeiXinPayUrl(orderMap);
    }

    /**
     * 获取微信支付订单的结果
     *
     * @param orderId 订单id
     * @return java.util.Map<java.lang.String, java.lang.String>
     */
    @GetMapping(value = "/getWeiXinPayResult")
    public Map<String, String> getWeiXinPayResult(@RequestParam String orderId) {
        return weiXinPayService.getWeiXinPayResult(orderId);
    }

    /**
     * 关闭交易
     *
     * @param orderId 订单id
     * @return java.util.Map<java.lang.String, java.lang.String>
     */
    @GetMapping(value = "/closePay")
    public Map<String, String> closePay(@RequestParam("orderId") String orderId) {
        return weiXinPayService.closePay(orderId);
    }

    /**
     * 微信回调通知的接口
     *
     * @param request 请求对象
     * @return java.lang.String
     */
    @RequestMapping(value = "/callback/notify")
    public String callbackNotifyUrl(HttpServletRequest request) throws Exception {
        //返回结果初始化
        Map<String, String> result = new HashMap<>(2);
        result.put("return_code", "SUCCESS");
        result.put("return_msg", "OK");

//        String message = "{\"transaction_id\":\"4200001492202205108879249874\"," +
//                "\"nonce_str\":\"5a5b408c7611468f9ccae3406d19baa9\"," +
//                "\"bank_type\":\"OTHERS\"," +
//                "\"openid\":\"oHwsHuCEdRHPShc_thV4Z4GL3umg\"," +
//                "\"sign\":\"242E74F1B8448C30A16D2996FB1275B7\"," +
//                "\"fee_type\":\"CNY\"," +
//                "\"mch_id\":\"1558950191\"," +
//                "\"cash_fee\":\"1\"," +
//                "\"out_trade_no\":\"1\"," +
//                "\"appid\":\"wx74862e0dfcf69954\"," +
//                "\"total_fee\":\"1\"," +
//                "\"trade_type\":\"NATIVE\"," +
//                "\"result_code\":\"SUCCESS\"," +
//                "\"time_end\":\"20220510225955\"," +
//                "\"is_subscribe\":\"N\"," +
//                "\"return_code\":\"SUCCESS\"}";
        // 将支付结果转换为map
        Map<String, String> resultMap = getResultMap(request);
        String message = JSONObject.toJSONString(resultMap);

        // 获取附加参，反序列化
        Map<String,String> attach = JSONObject.parseObject(resultMap.get("attach"), Map.class);

        // 发送支付结果的消息----存在耦合---------TODO---待优化
        rabbitTemplate.convertAndSend(
                attach.get("exchange"),
                attach.get("routingKey"),
                message);

        return WXPayUtil.mapToXml(result);
    }

    /**
     * 将支付结果转换为map
     *
     * @param request 请求对象
     * @return java.util.Map<java.lang.String, java.lang.String>
     */
    private Map<String, String> getResultMap(HttpServletRequest request) throws Exception {
        // 获取微信支付异步通知的结果输入流
        ServletInputStream inputStream = request.getInputStream();
        // 定义输入流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 定义缓存区
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        // 将结果转换为map
        return WXPayUtil.xmlToMap(outputStream.toString());
    }

}
